const {
  program
} = require('commander');
const inquirer = require('inquirer')
const config = require('../config/config')
const downloadTemplate = require('./download')
const compile = require('../utils/compile')
const writeToFile = require('../utils/writeToFile')
const path = require('path')
module.exports = {
  //创建项目
  async createProgramAction(programName, argv) {
    const opts = program.opts()
    let framework = ''
    //选择不同的框架
    if (!opts.framework) {
      console.log('请选择框架')
      const answer = await inquirer.prompt([{
        type: 'list',
        name: 'framework',
        choices: config.framwork,
        message: '请选择你所使用的框架'
      }])
      framework = answer.framework
    } else {
      framework = opts.framework
    }
    console.log('你选择的框架是：' + framework)
    //根据选择的框架拉取对应模板
    downloadTemplate(config.foramworkUrl[framework], programName)
  },
  //生成组件
  async createComponentAction(componentName, dest) {
    //编译模板
    const result = await compile('vue-component.ejs', {
      name: componentName,
      lowerName: componentName.toLowerCase()
    })
    const filePath = path.resolve(process.cwd() + "/" + dest + '/' + componentName + '.vue')
    // //写入文件
    writeToFile(filePath, result).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  },
  //生成页面
  async createPageAction(pageName, dest) {
    const data = {
      name: pageName,
      lowerName: pageName.toLowerCase()
    }
    //编译模板（pageName.vue,router.js）
    const pageResult = await compile('vue-component.ejs', data)
    const routerResult = await compile('vue-router.ejs', data)
    const pagePath = process.cwd() + "/" + dest + "/" + pageName + "/" + pageName + ".vue"
    const routerPath = process.cwd() + "/" + dest + "/" + pageName + "/router.js"
    //写入文件
    Promise.all([writeToFile(pagePath, pageResult), writeToFile(routerPath, routerResult)]).then(() => {
      console.log('创建页面成功')
    }).catch(() => {
      console.log('创建页面失败')
    })
  },
  //生成vuex模块
  async createStoreAction(storeName, dest) {
    //编译模板（types.js,index.js）
    const storeResult = await compile('vue-store.ejs')
    const typesResult = await compile('vue-types.ejs')
    //路径
    const storePath = process.cwd() + "/" + dest + "/" + storeName + "/index.js"
    const typesPath = process.cwd() + "/" + dest + "/" + storeName + "/types.js"
    //写入文件
    Promise.all([writeToFile(storePath, storeResult), writeToFile(typesPath, typesResult)]).then(() => {
      console.log('添加vuex模块成功')
    }).catch(() => {
      console.log('添加vuex模块失败')
    })
  }
}